package org.dragon.services.impls;

import jakarta.annotation.Resource;
import org.dragon.commons.Times;
import org.dragon.mappers.RoleExtendMapper;
import org.dragon.models.Permission;
import org.dragon.models.Role;
import org.dragon.services.RoleService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Author:     Zhao Yan
 * DateTime:   2023/5/22 9:13
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleExtendMapper roleExtendMapper;

    @Override
    public List<Role> findRoles(String accountId) {
        return roleExtendMapper.findRoles(accountId);
    }

    @Override
    public List<Permission> findPermissions(Long roleId) {
        return roleExtendMapper.findPermissions(roleId);
    }

    @Cacheable(value = "roles", key = "#id", sync = true)
    @Override
    public Role findById(Long id) {
        return roleExtendMapper.selectByPrimaryKey(id);
    }

    @CachePut(value = "roles", key = "#role.id")
    @Override
    public void save(Role role) {
        if (role != null) {
            if (role.getId() == null) {
                role.setCreateTime(Times.now());
                roleExtendMapper.insert(role);
            } else {
                roleExtendMapper.updateByPrimaryKey(role);
            }
        }
    }

    // 驱逐
    @CacheEvict(value = "roles", key = "#role.id")
    @Override
    public void delete(Role role) {
        if (role != null && role.getId() != null)
            roleExtendMapper.deleteByPrimaryKey(role.getId());
    }
}
